#!/bin/bash

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 显示标题
echo -e "${BLUE}=========================================${NC}"
echo -e "${BLUE}   SMG-UI 前端系统 - Docker镜像构建脚本   ${NC}"
echo -e "${BLUE}=========================================${NC}"

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo -e "${RED}错误: Docker未安装。请先安装Docker。${NC}"
    exit 1
fi

# 检查buildx是否可用
if ! docker buildx version &> /dev/null; then
    echo -e "${RED}错误: Docker buildx未安装或不可用。${NC}"
    echo -e "${YELLOW}请确保您的Docker版本支持buildx功能。${NC}"
    exit 1
fi

# 设置默认值
IMAGE_NAME="smg-ui"
IMAGE_TAG="latest"
DOCKERFILE="./Dockerfile"
BUILD_CONTEXT="."
NO_CACHE=false
COMPOSE_BUILD=false
CLEAN_OLD=false
VERBOSE=false
PUSH_TO_ALIYUN=false

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        -n|--name)
        IMAGE_NAME="$2"
        shift
        shift
        ;;
        -t|--tag)
        IMAGE_TAG="$2"
        shift
        shift
        ;;
        -f|--file)
        DOCKERFILE="$2"
        shift
        shift
        ;;
        -c|--context)
        BUILD_CONTEXT="$2"
        shift
        shift
        ;;
        --no-cache)
        NO_CACHE=true
        shift
        ;;
        --compose)
        COMPOSE_BUILD=true
        shift
        ;;
        --clean)
        CLEAN_OLD=true
        shift
        ;;
        --aliyun)
        PUSH_TO_ALIYUN=true
        shift
        ;;
        -v|--verbose)
        VERBOSE=true
        shift
        ;;
        -h|--help)
        echo -e "用法: $0 [选项]"
        echo -e "选项:"
        echo -e "  -n, --name NAME      设置镜像名称 (默认: smg-ui)"
        echo -e "  -t, --tag TAG        设置镜像标签 (默认: latest)"
        echo -e "  -f, --file FILE      指定Dockerfile路径 (默认: ./Dockerfile)"
        echo -e "  -c, --context DIR    指定构建上下文目录 (默认: .)"
        echo -e "  --no-cache           不使用缓存构建镜像"
        echo -e "  --compose            使用docker-compose构建"
        echo -e "  --clean              构建前清理旧的镜像"
        echo -e "  --aliyun             构建后自动推送到阿里云镜像仓库"
        echo -e "  -v, --verbose        显示详细构建日志"
        echo -e "  -h, --help           显示此帮助信息"
        exit 0
        ;;
        *)
        echo -e "${RED}未知选项: $1${NC}"
        echo -e "使用 '$0 --help' 获取更多信息"
        exit 1
        ;;
    esac
done

# 检查Dockerfile是否存在
if [ ! -f "$DOCKERFILE" ]; then
    echo -e "${RED}错误: 未找到Dockerfile文件: $DOCKERFILE${NC}"
    exit 1
fi

# 检查前端构建目录是否存在
if [ ! -d "dist" ]; then
    echo -e "${YELLOW}警告: dist目录不存在，前端可能未构建${NC}"
    echo -e "${YELLOW}您是否需要先构建前端项目? (y/n)${NC}"
    read -r build_frontend
    if [[ $build_frontend =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}正在构建前端项目...${NC}"
        # 根据项目实际情况调整构建命令
        npm run build
        if [ $? -ne 0 ]; then
            echo -e "${RED}前端项目构建失败。请检查构建错误。${NC}"
            exit 1
        fi
    else
        echo -e "${YELLOW}继续构建Docker镜像，但可能会失败如果dist目录不存在。${NC}"
    fi
fi

# 启用BuildKit
export DOCKER_BUILDKIT=1

# 创建并使用buildx构建器
if ! docker buildx inspect mybuilder &> /dev/null; then
    echo -e "${GREEN}创建新的buildx构建器...${NC}"
    docker buildx create --name mybuilder --use
else
    echo -e "${GREEN}使用现有的buildx构建器...${NC}"
    docker buildx use mybuilder
fi

# 显示架构选择菜单
echo -e "${BLUE}请选择目标架构:${NC}"
echo -e "  ${GREEN}1) amd64 (Intel/AMD处理器)${NC}"
echo -e "  ${GREEN}2) arm64 (Apple M1/M2芯片或ARM处理器)${NC}"
echo -e "  ${GREEN}3) 同时构建两种架构${NC}"
echo -e "  ${GREEN}4) 退出${NC}"

read -r -p "请输入选项 [1-4]: " choice

# 根据用户选择的架构修改镜像名称
case $choice in
    1)
        PLATFORM="linux/amd64"
        ARCH_DESC="amd64"
        FULL_IMAGE_NAME="${IMAGE_NAME}-amd64:${IMAGE_TAG}"
        ;;
    2)
        PLATFORM="linux/arm64"
        ARCH_DESC="arm64"
        FULL_IMAGE_NAME="${IMAGE_NAME}-arm64:${IMAGE_TAG}"
        ;;
    3)
        PLATFORM="linux/amd64,linux/arm64"
        ARCH_DESC="多架构(amd64+arm64)"
        FULL_IMAGE_NAME="${IMAGE_NAME}-multi:${IMAGE_TAG}"
        ;;
    4)
        echo -e "${BLUE}已取消构建。${NC}"
        exit 0
        ;;
    *)
        echo -e "${RED}无效选项。退出。${NC}"
        exit 1
        ;;
esac

# 询问是否需要推送到仓库
echo -e "${BLUE}是否需要推送到Docker仓库? (y/n)${NC}"
read -r push_to_registry

if [[ $push_to_registry =~ ^[Yy]$ ]]; then
    # 定义常用的Docker仓库地址
    echo -e "${BLUE}请选择Docker仓库地址:${NC}"
    echo -e "  ${GREEN}1) registry.cn-shanghai.aliyuncs.com/etech-vip${NC} (阿里云上海)"
    echo -e "  ${GREEN}2) registry.cn-hangzhou.aliyuncs.com/etech-vip${NC} (阿里云杭州)"
    echo -e "  ${GREEN}3) registry.cn-beijing.aliyuncs.com/etech-vip${NC} (阿里云北京)"
    echo -e "  ${GREEN}4) docker.io/username${NC} (DockerHub)"
    echo -e "  ${GREEN}5) 自定义仓库地址${NC}"
    
    read -r -p "请输入选项 [1-5] (默认: 1): " registry_choice
    registry_choice=${registry_choice:-1}
    
    case $registry_choice in
        1)
            registry="registry.cn-shanghai.aliyuncs.com/etech-vip"
            login_server="registry.cn-shanghai.aliyuncs.com"
            ;;
        2)
            registry="registry.cn-hangzhou.aliyuncs.com/etech-vip"
            login_server="registry.cn-hangzhou.aliyuncs.com"
            ;;
        3)
            registry="registry.cn-beijing.aliyuncs.com/etech-vip"
            login_server="registry.cn-beijing.aliyuncs.com"
            ;;
        4)
            echo -e "${BLUE}请输入DockerHub用户名:${NC}"
            read -r username
            registry="docker.io/$username"
            login_server="docker.io"
            ;;
        5)
            echo -e "${BLUE}请输入完整的Docker仓库地址:${NC}"
            read -r registry
            # 提取登录服务器地址
            login_server=$(echo $registry | cut -d'/' -f1)
            ;;
        *)
            echo -e "${RED}无效选项。使用默认值。${NC}"
            registry="registry.cn-shanghai.aliyuncs.com/etech-vip"
            login_server="registry.cn-shanghai.aliyuncs.com"
            ;;
    esac

    if [ -z "$registry" ]; then
        echo -e "${RED}未提供仓库地址。退出。${NC}"
        exit 1
    fi

    echo -e "${GREEN}已选择仓库地址: ${registry}${NC}"
    FULL_IMAGE_NAME="${registry}/${FULL_IMAGE_NAME}"
    PUSH_ARG="--push"

    echo -e "${YELLOW}您可能需要先登录到Docker仓库:${NC}"
    echo -e "${YELLOW}docker login ${login_server}${NC}"
    
    # 询问是否需要登录
    echo -e "${BLUE}是否需要现在登录? (y/n)${NC}"
    read -r do_login
    if [[ $do_login =~ ^[Yy]$ ]]; then
        docker login ${login_server}
    fi
else
    PUSH_ARG="--load"

    # 多架构构建必须推送到仓库
    if [ "$choice" -eq 3 ]; then
        echo -e "${RED}多架构构建必须推送到仓库。请重新运行脚本并选择推送选项。${NC}"
        exit 1
    fi
fi

# 显示构建信息
echo -e "${BLUE}=========================================${NC}"
echo -e "${BLUE}构建信息:${NC}"
echo -e "${BLUE}  镜像名称: ${NC}${FULL_IMAGE_NAME}"
echo -e "${BLUE}  目标架构: ${NC}${ARCH_DESC}"
echo -e "${BLUE}  Dockerfile: ${NC}${DOCKERFILE}"
echo -e "${BLUE}  构建上下文: ${NC}${BUILD_CONTEXT}"
echo -e "${BLUE}  不使用缓存: ${NC}$([ "$NO_CACHE" = true ] && echo "是" || echo "否")"
echo -e "${BLUE}  使用Docker Compose: ${NC}$([ "$COMPOSE_BUILD" = true ] && echo "是" || echo "否")"
echo -e "${BLUE}  清理旧镜像: ${NC}$([ "$CLEAN_OLD" = true ] && echo "是" || echo "否")"
echo -e "${BLUE}  详细日志: ${NC}$([ "$VERBOSE" = true ] && echo "是" || echo "否")"
echo -e "${BLUE}  推送到阿里云: ${NC}$([ "$PUSH_TO_ALIYUN" = true ] && echo "是" || echo "否")"
if [[ $push_to_registry =~ ^[Yy]$ ]]; then
    echo -e "${BLUE}  操作: ${NC}构建并推送到仓库"
else
    echo -e "${BLUE}  操作: ${NC}仅构建本地镜像"
fi
echo -e "${BLUE}=========================================${NC}"

# 确认构建
echo -e "${YELLOW}确认以上信息并开始构建? (y/n)${NC}"
read -r confirm

if [[ ! $confirm =~ ^[Yy]$ ]]; then
    echo -e "${BLUE}已取消构建。${NC}"
    exit 0
fi

# 清理旧镜像（如果需要）
if [ "$CLEAN_OLD" = true ]; then
    echo -e "${GREEN}清理旧镜像...${NC}"
    docker images | grep "$IMAGE_NAME" | grep "$IMAGE_TAG" | awk '{print $3}' | xargs -r docker rmi -f
fi

# 构建命令参数
BUILD_ARGS=""
if [ "$NO_CACHE" = true ]; then
    BUILD_ARGS="$BUILD_ARGS --no-cache"
fi

if [ "$VERBOSE" = true ]; then
    BUILD_ARGS="$BUILD_ARGS --progress=plain"
else
    BUILD_ARGS="$BUILD_ARGS --progress=auto"
fi

# 定义用户提供的镜像源数组
REGISTRY_MIRRORS=(
    "docker.1ms.run"
    "docker.anyhub.us.kg"
    "docker.fxxk.dedyn.io"
    "docker.sunzishaokao.com"
    "docker-mirror.aigc2d.com"
    "dockerhub.icu"
    "hub.rat.dev"
    "docker.wanpeng.top"
    "doublezonline.cloud"
    "docker.mrxn.net"
    "dislabaiot.xyz"
    "docker-mirror.aigc2d.com"
)

# 默认使用第一个镜像源
DEFAULT_REGISTRY="${REGISTRY_MIRRORS[0]}"

# 开始构建
echo -e "${GREEN}开始构建Docker镜像...${NC}"

# 使用docker-compose构建
if [ "$COMPOSE_BUILD" = true ]; then
    echo -e "${GREEN}使用Docker Compose构建...${NC}"
    if ! command -v docker-compose &> /dev/null; then
        echo -e "${RED}错误: Docker Compose未安装。${NC}"
        exit 1
    fi
    docker-compose build $BUILD_ARGS
else
    # 使用docker buildx构建，传递 --build-arg BASE_REGISTRY
    echo -e "${GREEN}使用镜像源: ${DEFAULT_REGISTRY}${NC}"
    docker buildx build --platform $PLATFORM -t $FULL_IMAGE_NAME -f $DOCKERFILE $BUILD_CONTEXT $PUSH_ARG $BUILD_ARGS --build-arg BASE_REGISTRY="$DEFAULT_REGISTRY"
fi

# 检查构建结果
if [ $? -eq 0 ]; then
    echo -e "${GREEN}=========================================${NC}"
    echo -e "${GREEN}Docker镜像构建成功!${NC}"
    echo -e "${GREEN}镜像名称: ${FULL_IMAGE_NAME}${NC}"
    echo -e "${GREEN}目标架构: ${ARCH_DESC}${NC}"

    if [[ $push_to_registry =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}镜像已推送到仓库。${NC}"
    else
        echo -e "${GREEN}镜像已保存在本地。${NC}"
        
        # 询问用户是否需要推送到远程仓库
        echo -e "${BLUE}是否需要现在推送到远程仓库? (y/n)${NC}"
        read -r push_now
        
        if [[ $push_now =~ ^[Yy]$ ]]; then
            # 定义常用的Docker仓库地址
            echo -e "${BLUE}请选择Docker仓库地址:${NC}"
            echo -e "  ${GREEN}1) registry.cn-shanghai.aliyuncs.com/etech-vip${NC} (阿里云上海)"
            echo -e "  ${GREEN}2) registry.cn-hangzhou.aliyuncs.com/etech-vip${NC} (阿里云杭州)"
            echo -e "  ${GREEN}3) registry.cn-beijing.aliyuncs.com/etech-vip${NC} (阿里云北京)"
            echo -e "  ${GREEN}4) docker.io/username${NC} (DockerHub)"
            echo -e "  ${GREEN}5) 自定义仓库地址${NC}"
            
            read -r -p "请输入选项 [1-5] (默认: 1): " registry_choice
            registry_choice=${registry_choice:-1}
            
            case $registry_choice in
                1)
                    registry="registry.cn-shanghai.aliyuncs.com/etech-vip"
                    login_server="registry.cn-shanghai.aliyuncs.com"
                    ;;
                2)
                    registry="registry.cn-hangzhou.aliyuncs.com/etech-vip"
                    login_server="registry.cn-hangzhou.aliyuncs.com"
                    ;;
                3)
                    registry="registry.cn-beijing.aliyuncs.com/etech-vip"
                    login_server="registry.cn-beijing.aliyuncs.com"
                    ;;
                4)
                    echo -e "${BLUE}请输入DockerHub用户名:${NC}"
                    read -r username
                    registry="docker.io/$username"
                    login_server="docker.io"
                    ;;
                5)
                    echo -e "${BLUE}请输入完整的Docker仓库地址:${NC}"
                    read -r registry
                    # 提取登录服务器地址
                    login_server=$(echo $registry | cut -d'/' -f1)
                    ;;
                *)
                    echo -e "${RED}无效选项。使用默认值。${NC}"
                    registry="registry.cn-shanghai.aliyuncs.com/etech-vip"
                    login_server="registry.cn-shanghai.aliyuncs.com"
                    ;;
            esac
            
            # 询问镜像名称和标签
            echo -e "${BLUE}请输入镜像名称 (默认: smg-ui):${NC}"
            read -r repo_name
            repo_name=${repo_name:-smg-ui}
            
            echo -e "${BLUE}请输入镜像标签 (默认: latest):${NC}"
            read -r tag_name
            tag_name=${tag_name:-latest}
            
            REMOTE_IMAGE_NAME="${registry}/${repo_name}:${tag_name}"
            
            echo -e "${GREEN}正在为镜像添加远程标签: ${REMOTE_IMAGE_NAME}${NC}"
            docker tag ${FULL_IMAGE_NAME} ${REMOTE_IMAGE_NAME}
            
            echo -e "${YELLOW}您可能需要先登录到Docker仓库:${NC}"
            echo -e "${YELLOW}docker login ${login_server}${NC}"
            
            # 询问是否需要先登录
            echo -e "${BLUE}是否需要先登录Docker仓库? (y/n)${NC}"
            read -r login_registry
            
            if [[ $login_registry =~ ^[Yy]$ ]]; then
                docker login ${login_server}
            fi
            
            # 推送镜像到远程仓库
            echo -e "${GREEN}正在推送镜像到远程仓库...${NC}"
            docker push ${REMOTE_IMAGE_NAME}
            
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}镜像已成功推送到远程仓库: ${REMOTE_IMAGE_NAME}${NC}"
            else
                echo -e "${RED}推送到远程仓库失败，请检查错误信息。${NC}"
            fi
        fi
        
        # 如果命令行参数指定了推送到阿里云，或者询问用户是否需要推送
        if [ "$PUSH_TO_ALIYUN" = true ]; then
            push_to_aliyun="y"
        else
            echo -e "${BLUE}是否需要推送到阿里云镜像仓库? (y/n)${NC}"
            read -r push_to_aliyun
        fi
        
        if [[ $push_to_aliyun =~ ^[Yy]$ ]]; then
            # 定义常用的阿里云仓库地址
            echo -e "${BLUE}请选择阿里云区域:${NC}"
            echo -e "  ${GREEN}1) registry.cn-shanghai.aliyuncs.com${NC} (上海)"
            echo -e "  ${GREEN}2) registry.cn-hangzhou.aliyuncs.com${NC} (杭州)"
            echo -e "  ${GREEN}3) registry.cn-beijing.aliyuncs.com${NC} (北京)"
            
            read -r -p "请输入选项 [1-3] (默认: 1): " aliyun_region_choice
            aliyun_region_choice=${aliyun_region_choice:-1}
            
            case $aliyun_region_choice in
                1)
                    aliyun_registry_base="registry.cn-shanghai.aliyuncs.com"
                    ;;
                2)
                    aliyun_registry_base="registry.cn-hangzhou.aliyuncs.com"
                    ;;
                3)
                    aliyun_registry_base="registry.cn-beijing.aliyuncs.com"
                    ;;
                *)
                    echo -e "${RED}无效选项。使用默认值。${NC}"
                    aliyun_registry_base="registry.cn-shanghai.aliyuncs.com"
                    ;;
            esac
            
            # 询问命名空间和仓库名
            echo -e "${BLUE}请输入阿里云命名空间 (默认: etech-vip):${NC}"
            read -r aliyun_namespace
            aliyun_namespace=${aliyun_namespace:-etech-vip}
            
            echo -e "${BLUE}请输入镜像仓库名 (默认: smg-ui):${NC}"
            read -r aliyun_repo
            aliyun_repo=${aliyun_repo:-smg-ui}
            
            echo -e "${BLUE}请输入镜像标签 (默认: latest):${NC}"
            read -r aliyun_tag
            aliyun_tag=${aliyun_tag:-latest}
            
            ALIYUN_REGISTRY="${aliyun_registry_base}/${aliyun_namespace}/${aliyun_repo}:${aliyun_tag}"
            
            echo -e "${GREEN}正在为镜像添加阿里云标签: ${ALIYUN_REGISTRY}${NC}"
            docker tag ${FULL_IMAGE_NAME} ${ALIYUN_REGISTRY}
            
            echo -e "${GREEN}正在推送镜像到阿里云...${NC}"
            echo -e "${YELLOW}您可能需要先登录到阿里云Docker仓库:${NC}"
            echo -e "${YELLOW}docker login ${aliyun_registry_base}${NC}"
            
            # 询问是否需要先登录
            echo -e "${BLUE}是否需要先登录阿里云Docker仓库? (y/n)${NC}"
            read -r login_aliyun
            
            if [[ $login_aliyun =~ ^[Yy]$ ]]; then
                docker login ${aliyun_registry_base}
            fi
            
            # 推送镜像到阿里云
            docker push ${ALIYUN_REGISTRY}
            
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}镜像已成功推送到阿里云仓库: ${ALIYUN_REGISTRY}${NC}"
            else
                echo -e "${RED}推送到阿里云仓库失败，请检查错误信息。${NC}"
            fi
        fi
    fi

    echo -e "${GREEN}=========================================${NC}"
else
    echo -e "${RED}=========================================${NC}"
    echo -e "${RED}Docker镜像构建失败!${NC}"
    
    # 提供重试选项，使用其他镜像源
    echo -e "${YELLOW}是否尝试使用其他镜像源重新构建? (y/n)${NC}"
    read -r try_other_mirror
    
    if [[ $try_other_mirror =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}可用的镜像源:${NC}"
        for i in "${!REGISTRY_MIRRORS[@]}"; do
            echo -e "  ${GREEN}$((i+1))) ${REGISTRY_MIRRORS[$i]}${NC}"
        done
        
        read -r -p "请选择镜像源 [1-${#REGISTRY_MIRRORS[@]}]: " mirror_choice
        
        if [[ $mirror_choice -ge 1 && $mirror_choice -le ${#REGISTRY_MIRRORS[@]} ]]; then
            SELECTED_REGISTRY="${REGISTRY_MIRRORS[$((mirror_choice-1))]}"
            echo -e "${GREEN}使用镜像源: ${SELECTED_REGISTRY}${NC}"
            
            # 重新尝试构建
            echo -e "${GREEN}重新尝试构建...${NC}"
            docker buildx build --platform $PLATFORM -t $FULL_IMAGE_NAME -f $DOCKERFILE $BUILD_CONTEXT $PUSH_ARG $BUILD_ARGS --build-arg BASE_REGISTRY="$SELECTED_REGISTRY"
            
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}镜像构建成功: ${FULL_IMAGE_NAME}${NC}"
            else
                echo -e "${RED}镜像构建再次失败，请检查网络或手动设置镜像源${NC}"
                exit 1
            fi
        else
            echo -e "${RED}无效选择，退出构建${NC}"
            exit 1
        fi
    else
        echo -e "${RED}请检查上述错误信息。${NC}"
        echo -e "${RED}=========================================${NC}"
        exit 1
    fi
fi

# 添加执行权限
chmod +x "$0"

exit 0